package com.gome.wechat.program.controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.gome.wechat.program.common.util.CommonUtil;
import com.gome.wechat.program.dto.UserDto;
import com.gome.wechat.program.service.queryservice.UserQueryService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liwei113 on 2017/11/1 0001.
 */
@Api("微信")
@RestController
@RequestMapping(value = "/wechat", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WeChatController {

    private static final Logger logger = LoggerFactory.getLogger(WeChatController.class);

    @Autowired
    UserQueryService userQueryService;
    /**
     * 获取openId
     * 开发人员：wangql
     * 开发时间：2017-6-14
     * @param request
     * @param response
     */
    @ResponseBody
    @GetMapping(value="/getOpenId")
    public Map<String, Object> getOpenId(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "code") String code){
        Map<String, Object> map = new HashMap<String, Object>();
        String status = "1";
        String msg = "ok";
        String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        try {
            if(StringUtils.isEmpty(code)){
                status = "0";//失败状态
                msg = "code为空";
            }else {
                String requestUrl = WX_URL.replace("APPID", "wxe9f73166f6dfdd85").
                        replace("SECRET", "284be746d5fe0e045708a3d83f2e2cdf").replace("JSCODE", code);
                logger.info(requestUrl);
                // 发起GET请求获取凭证
                JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
                if (jsonObject != null) {
                    try {
                        map.put("openid", jsonObject.getString("openid"));
                        map.put("session_key", jsonObject.getString("session_key"));
                        UserDto userDto = userQueryService.findByOpenId(jsonObject.getString("openid"));
                        map.put("user", userDto);
                    } catch (JSONException e) {
                        // 获取token失败
                        status = "0";
                        msg = "code无效";
                    }
                }else {
                    status = "0";
                    msg = "code无效";
                }
            }
            map.put("status", status);
            map.put("msg", msg);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return map;
        }
        return map;
    }
}
